package thread;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;


class MyBlockingQueue1 {
    //存储数据
    private String[] str;

    //锁对象
    private final Object locker = new Object();

    //数组中数据的实际个数
    private int size = 0;

    //拿出元素的下标
    private int head = 0;

    //添加元素的下标
    private int tail = 0;


    public MyBlockingQueue1(int capacity) {
        str = new String[capacity];
    }

    public void put(String data) throws InterruptedException {
        synchronized (locker) {
            //队列满
            while (size >= str.length) {
                locker.wait();
            }
            str[tail] = data;
            tail++;
            size++;
            //tail溢出数组，让tail从起始位置开始
            if (tail >= str.length) {
                tail = 0;
            }
            //唤醒队列为空的wait
            locker.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized (locker) {
            //队列空
            while(size == 0) {
                locker.wait();
            }
            String ret = str[head];
            head++;
            size--;
            //head溢出数组，让head从起始位置开始
            if (head >= str.length) {
                head = 0;
            }
            //唤醒队列为满的wait
            locker.notify();
            return ret;
        }
    }
}

public class Demo58 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue1 queue = new MyBlockingQueue1(4);
        Thread t1 = new Thread(() -> {
            int n = 0;
            while (true) {
                    try {
                        queue.put(n +"");
                        System.out.println("填入数据："+n);
                        n++;
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
            }
        });
        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    String data = queue.take();
                    System.out.println("取出数据:" + data );
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });
        t1.start();
        t2.start();
    }
}
